/**
 * Copyright 2018 贝壳开源 http://www.beikbank.com
 */

package com.beikbank.modules.sys.shiro;


import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 认证
 * season
 */
@Component
public class UserRealm extends AuthorizingRealm {

    /**
     * 授权(验证权限时调用)
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Set<String> permsSet = new HashSet<>();
		//数据库查找，进行相关赋值//todo
		String uesr = (String)principals.getPrimaryPrincipal();
//		if (uesr.equals("admin")) {
//			permsSet.add("user:test");
//		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permsSet);
		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;

		//查询用户信息,实际是从数据库查找出来的
		String username = token.getUsername();
		String toeknCr = new String(token.getPassword());
		String salt = "YzcmCZNvbXocrsz9dm8e";
		String password = ShiroUtils.sha256(toeknCr, salt);
//		String password = "e1153123d7d180ceeb820d577ff119876678732a68eef4e6ffc0b1f06a01f91b";
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(salt), getName());
		return info;
	}

	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
		shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
		shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
		super.setCredentialsMatcher(shaCredentialsMatcher);
	}
}
